<!-- 客户地区分布呼叫排行 -->
<template>
	<div id="dayCallAnalysis">
		<div class="count card">
			<p class="statis-title">今日调解通话量</p>
			<div class="count-content">
				<div class="count-item" v-for="item in countData" :key="item">
					<div class="count-title">{{ item.label }}</div>
					<div class="count-num">
						<span>{{ item.value }}</span>
						<span>&nbsp;{{ item.unit }}</span>
					</div>
					<!-- <div class="count-rate">
						月环比 {{ item.increase }}&nbsp;
						<RiseOutlined style="color: #389e0d; font-weight: 600" v-show="!item.increase.includes('-')" />
						<FallOutlined style="color: #d9363e; font-weight: 800" v-show="item.increase.includes('-')" />
					</div> -->
				</div>
				<!-- <div class="count-item" v-for="item in testcountData" :key="item">
					<div class="count-title">{{ item.label }}</div>
					<div class="count-num">
						<span v-if="item.type === 'duration'">{{ item.value.toFixed(1) }}</span>
						<span v-else>{{ item.value }}</span>
					</div>
					<div class="count-rate">月环比 {{ item.increase }}%</div>
				</div> -->
			</div>
		</div>
		<div class="statis">
			<div class="statis-order w-1/3 card">
				<p class="statis-title">调解案件地区排名</p>
				<vue3ScrollSeamless class="statis-order-list" :classOptions="classOptions" :dataList="orderList">
					<div class="list-item" v-for="(item, i) in orderList" :key="i">
						<div class="list-item-num" :style="{ background: getOrderColor(item.order) }">{{ item.order }}</div>
						<div class="list-item-name">{{ item.name }}</div>
						<div class="list-item-bar">
							<p :style="{ width: getOrderRate(item.rate) }"></p>
						</div>
						<div>{{ item.rate }}%</div>
					</div>
				</vue3ScrollSeamless>
				<!-- <div class="statis-order-list">
					<div class="list-item" v-for="(item, i) in orderList" :key="i">
						<div class="list-item-num" :style="{ background: getOrderColor(item.order) }">{{ item.order }}</div>
						<div class="list-item-name">{{ item.name }}</div>
						<div class="list-item-bar">
							<p :style="{ width: getOrderRate(item.rate) }"></p>
						</div>
						<div>{{ item.rate }}%</div>
					</div>
				</div> -->
			</div>
			<div class="statis-map w-2/3 card">
				<p class="statis-title">调解案件全国分布情况</p>
				<div id="proviceMap"></div>
				<!-- 添加音频播放组件 -->
				<div class="audio-player" v-if="showAudioPlayer">
					<div class="player-header">
						<span>{{ curAreaInfo.area }} - {{ curAreaInfo.label }}</span>
						<span class="close-btn" @click="showAudioPlayer = false">×</span>
					</div>
					<audio
						controls
						controlsList="nodownload noplaybackrate"
						:src="currentAudioUrl"
						class="audio-control"
						ref="audioRef"
					></audio>
				</div>
			</div>
			<!-- 圆形图表 -->
			<div class="statis-callout card">
				<div class="total">
					<p class="statis-title">调解总数日环比</p>
					<div id="totalChart"></div>
				</div>
				<div class="duration">
					<p class="statis-title">调解总时长日环比（分钟）</p>
					<div id="durationChart"></div>
				</div>
			</div>
		</div>
	</div>
</template>
<script setup name="dayCallAnalysis">
	import { onMounted, nextTick, onUnmounted } from 'vue'
	import * as echarts from 'echarts'
	import chinaJson from '@/assets/map/china.json'
	import biChartApi from '@/api/bi/biChartApi.js'
	import { throttle } from 'lodash'
	import tool from '@/utils/tool.js'
	import { vue3ScrollSeamless } from 'vue3-scroll-seamless'
	// 处理地图数据
	chinaJson.features.forEach((item) => {
		item.properties.name = item.properties.name
			.replace('市', '')
			.replace('省', '')
			.replace('自治区', '')
			.replace('回族', '')
			.replace('维吾尔', '')
			.replace('壮族', '')
			.replace('特别行政区', '')
	})
	// ===========================================DATA======================================================
	const orderColor = ['#EEB140', '#B2BDCF', '#C5A17D', '#3F4FC8']
	let colorList = ['#0958d9', '#1677ff', '#4096ff', '#69b1ff', '#91caff', '#bae0ff'] //antdv色值
	let dayChartDom
	let totalChartDom
	let durationChartDom
	let dayMapChart
	let totalChart
	let durationChart
	let dayMapOption = ref({
		// 标题配置
		title: {
			textStyle: {
				color: '#fff'
			}
		},
		// 提示框配置
		tooltip: {
			trigger: 'item', // 数据项触发，鼠标移到省份上时显示
			backgroundColor: 'rgba(24, 35, 62, 0.9)',
			borderColor: '#1E4B9C',
			textStyle: {
				color: '#fff'
			},
			padding: [10, 15],
			enterable: true,
			formatter: function (params) {
				if (!params.value) {
					return
				}
				let html = `
								<div class="tooltip-header">
									<p>
										${params.name}
									</p>
									<p>
										实时调解案件:&nbsp;${tool.formatNumber(params.value)}&nbsp;件
									</p>
								</div>
								<div class="tooltip-scroll">
									<div class="scroll-content">
								`
				// 重复两次数据以实现无缝滚动
				const repeatedData = [...audioList.value, ...audioList.value]
				repeatedData.forEach((item) => {
					html += `
								<div
									class="scroll-item"
									onmouseover="this.style.backgroundColor='rgba(87, 148, 247, 0.1)'"
									onmouseout="this.style.backgroundColor='transparent'"
									onclick="window.dayCallTooltipItemClick && window.dayCallTooltipItemClick('${params.name}', '${item.label}', '${item.url}')"
								>
									<span style="margin-right: 15px;">${item.label}</span>
									<span style="color: #5794F7;">${item.value}</span>
								</div>
							`
				})
				html += `
							</div>
						</div>
						<style>
							@keyframes scroll {
							0% { transform: translateY(0); }
							100% { transform: translateY(-50%); }
							}
							.tooltip-header {
								font-size: 16px;
								font-weight: bold;
								margin-bottom: 10px;
							}
							.tooltip-scroll {
								height: 200px;
								overflow: hidden;
							}
							.tooltip-scroll .scroll-content {
								transition: all 0.3s;
								animation: scroll 20s linear infinite;
								transform: translateZ(0);
								.scroll-item {
									display: flex;
									justify-content: space-between;
									margin: 5px 0;
									padding: 5px;
									cursor: pointer;
								}
							}
							.tooltip-scroll:hover .scroll-content {
								animation-play-state: paused;
								background: rgba(87, 148, 247, 0.05);
							}
						</style>
						`
				return html
			}
		},
		// 视觉映射组件
		visualMap: {
			// min: 0, // 最小值
			// max: 100000, // 最大值
			// text: ['High', 'Low'],
			// realtime: true,
			// calculable: true,
			show: false,
			inRange: {
				// color: ['#87B0F3', '#0B22C4'] // 深蓝到亮蓝的渐变
				color: ['#bae0ff','#4096ff','#1677ff','#0B22C4'] // 深蓝到亮蓝的渐变，色值顺序浅--》深
			},
			textStyle: {
				color: '#fff' // 文字颜色设为白色
			},
			top: 0
		},

		// 系列列表
		series: [
			{
				type: 'map',
				map: 'china_day_analysis',
				roam: true, // 添加此配置允许缩放平移
				zoom: 1.6, // 缩放比例
				center: [103.5, 35.5],
				scaleLimit: {
					// 缩放限制
					min: 1,
					max: 2
				},
				animationDuration: 1000, // 动画时长
				animationEasing: 'cubicOut', // 动画效果
				animationDurationUpdate: 1000,
				label: {
					show: true,
					fontSize: 8,
					color: '#fff'
				},
				itemStyle: {
					areaColor: '#142957',
					borderColor: '#1E4B9C',
					borderWidth: 1
				},
				emphasis: {
					label: {
						color: '#fff'
					},
					itemStyle: {
						areaColor: '#0066FF'
					}
				},
				// ... 选中的样式 ...
				// select: {
				// 	itemStyle: {
				// 		areaColor: '#EEB140', // 点击后的颜色
				// 		borderColor: '#fff', // 点击后的边框颜色
				// 		borderWidth: 2 // 点击后的边框宽度
				// 	},
				// 	label: {
				// 		color: '#000',
				// 		fontSize: 12
				// 	}
				// },
				data: [
					{ name: '广东', value: 900 },
					{ name: '北京', value: 800 },
					{ name: '上海', value: 700 },
					{ name: '浙江', value: 600 },
					{ name: '江苏', value: 500 },
					{ name: '福建', value: 400 },
					{ name: '山东', value: 300 },
					{ name: '河南', value: 200 },
					{ name: '湖北', value: 100 },
					{ name: '湖南', value: 50 },
					{ name: '安徽', value: 10 },
					{ name: '江西', value: 20 },
					{ name: '四川', value: 200 },
					{ name: '云南', value: 950 },
					{ name: '陕西', value: 800 },
					{ name: '重庆', value: 500 },
					{ name: '贵州', value: 600 },
					{ name: '台湾', value: 30 },
					{ name: '河北', value: 40 },
					{ name: '山西', value: 50 },
					{ name: '内蒙古', value: 620 },
					{ name: '辽宁', value: 70 },
					{ name: '吉林', value: 550 },
					{ name: '黑龙江', value: 10 },
					{ name: '甘肃', value: 20 },
					{ name: '青海', value: 30 },
					{ name: '宁夏', value: 40 },
					{ name: '新疆', value: 655 },
					{ name: '西藏', value: 60 },
					{ name: '广西', value: 70 },
					{ name: '海南', value: 800 }
				]
			}
		]
	})
	let totalOption = ref({
		series: [
			{
				type: 'liquidFill',
				data: [],
				radius: '80%',
				color: ['#3D76F6'],
				backgroundStyle: {
					color: 'transparent'
				},
				outline: {
					show: true,
					borderDistance: 8,
					itemStyle: {
						borderWidth: 2, // 设置边框粗细
						borderColor: '#2c4095' // 设置边框颜色
						// shadowBlur: 20, // 添加阴影效果
						// shadowColor: '#3D76F6'
					}
				},
				label: {
					fontSize: 32,
					fontWeight: 400,
					color: '#fff',
					formatter: (param) => {
						return param.value + '%'
					}
				},
				itemStyle: {
					opacity: 0.8
				},
				emphasis: {
					itemStyle: {
						opacity: 0.9
					}
				}
			}
		]
	})
	let durationOption = ref({
		series: [
			{
				type: 'pie',
				radius: ['65%', '85%'],
				avoidLabelOverlap: false,
				label: {
					show: true,
					position: 'center',
					formatter: (param) => {
						return param.value + '%'
					},
					fontSize: 32,
					color: '#fff'
				},
				data: [
					{
						value: 75,
						name: '已完成',
						itemStyle: {
							color: '#3D76F6'
						}
					},
					{
						value: 25,
						name: '未完成',
						itemStyle: {
							color: '#142957'
						}
					}
				]
			}
		]
	})
	let orderList = ref([])
	let baseNum = ref(0) //排行宽度计算基数
	let classOptions = ref({
		step: 0.1,
		hoverStop: true,
		limitMoveNum: 16
	})
	//统计展示数据
	let countData = ref([
		{
			id: 1,
			label: '今日线路数量',
			type: 'number',
			field: 'lineNum',
			value: 0,
			increaseField: 'lineMonthRatio',
			increase: '+0',
			unit: '条'
		},
		{
			id: 2,
			label: ' 今日客户地区分布',
			type: 'number',
			field: 'customerAreaNum',
			value: 0,
			increaseField: 'customerAreaMonthRatio',
			increase: '+0',
			unit: '个'
		},
		{
			id: 3,
			label: '今日调解总数',
			type: 'number',
			field: 'callNum',
			value: 0,
			increaseField: 'callNumMonthRatio',
			increase: '+0',
			unit: '个'
		},
		{
			id: 4,
			label: '今日调解总时长',
			type: 'duration',
			field: 'totalCallDuration',
			value: 0,
			increaseField: 'totalCallDurationMonthRatio',
			increase: '+0',
			unit: '分钟'
		}
	])
	// 添加音频播放相关的响应式数据
	const showAudioPlayer = ref(false)
	const curAreaInfo = ref({
		area: '',
		label: '',
		value: ''
	})
	const currentAudioUrl = ref('')
	const audioRef = ref(null)
	let audioList = ref([
		{
			label: '录音1',
			value: '10分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181853192379585302581744973599.wav'
		},
		{
			label: '录音2',
			value: '11分钟',
			url: 'https://saas-cti.htrxcall.com/recfile57/20250418/202504181901214454355703321744974081.wav'
		},
		{
			label: '录音3',
			value: '6分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181900060757595302341744974006.wav'
		},
		{
			label: '录音4',
			value: '20分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181902484385405301131744974168.wav'
		},
		{
			label: '录音5',
			value: '22分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181902484385405301131744974168.wav'
		},
		{
			label: '录音6',
			value: '21分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181902484385405301131744974168.wav'
		},
		{
			label: '录音7',
			value: '18分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181902484385405301131744974168.wav'
		},
		{
			label: '录音8',
			value: '14分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181902484385405301131744974168.wav'
		},
		{
			label: '录音9',
			value: '22分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181902484385405301131744974168.wav'
		},
		{
			label: '录音10',
			value: '19分钟',
			url: 'https://saas-cti.htrxcall.com/recfile53/20250418/202504181902484385405301131744974168.wav'
		}
	])
	// ===========================================WATCH=====================================================
	// ===========================================LIFECYCLE HOOKS===========================================
	onMounted(() => {
		window.dayCallTooltipItemClick = dayCallTooltipItemClick
		//绘制省份分布图--------------------------------
		// 注册地图数据
		echarts.registerMap('china_day_analysis', chinaJson)
		// 绘制水球图-----------------------------------
		totalChartDom = document.getElementById('totalChart')
		totalChart = echarts.init(totalChartDom)
		// 绘制环比图-----------------------------------
		durationChartDom = document.getElementById('durationChart')
		durationChart = echarts.init(durationChartDom)
		setTimeout(async () => {
			dayChartDom = document.querySelector('#dayCallAnalysis #proviceMap')
			// 初始化渲染器
			dayMapChart = echarts.init(dayChartDom)
			const biResult = await getData()
			// console.log('TODAY_CALL_ANALYSIS_DAY: ', biResult)
			// 顶部统计数据
			countData.value.forEach((item) => {
				item.increase = biResult[item.increaseField]
				switch (item.type) {
					case 'duration':
						item.value = tool.formatNumber(biResult[item.field].toFixed(2))
						break
					case 'rate':
						item.value = `${tool.formatNumber(biResult[item.field].toFixed(2))}%`
						break
					default:
						item.value = tool.formatNumber(biResult[item.field])
						break
				}
			})
			//处理排行榜数据
			biResult.customerArea.sort((a, b) => {
				return b.value - a.value
			})
			let orderData = []
			biResult.customerArea.forEach((item, i) => {
				orderData.push({
					order: i + 1,
					name: item.name,
					rate: (item.rate * 100).toFixed(2)
				})
			})
			orderList.value = orderData
			baseNum.value = orderList.value[0].rate + 10
			//处理地图数据
			dayMapOption.value.series[0].data = biResult.customerArea.map((item) => {
				return {
					name: item.name,
					value: item.value
				}
			})
			// 区间范围定义
			// dayMapOption.value.visualMap.min = Math.min(
			// 	...dayMapOption.value.series[0].data.map((item) => Number(item.value))
			// )
			dayMapOption.value.visualMap.max = Math.max(
				...dayMapOption.value.series[0].data.map((item) => Number(item.value))
			)
			dayMapChart.setOption(dayMapOption.value)
			// 点击事件监听
			dayMapChart.on('click', (params) => {
				console.log('省份信息:', params)
			})
			//调解总数日环比
			totalOption.value.series[0].data = [biResult.callTotalDayRatio]
			totalChart.setOption(totalOption.value)
			//调解总时长日环比
			durationOption.value.series[0].data[0].value = biResult.callTotalDurationDayRatio
			durationOption.value.series[0].data[1].value = 100 - biResult.callTotalDurationDayRatio
			durationChart.setOption(durationOption.value)
		}, 1000)
		// 自适应大小
		const dayCallResize = throttle(() => {
			setTimeout(() => {
				dayMapChart?.resize()
				totalChart?.resize()
				durationChart?.resize()
			}, 500)
		}, 200)
		window.addEventListener('resize', dayCallResize)
	})
	// 组件卸载时清理
	onUnmounted(() => {
		windowNaNpxoveEventListener('resize', dayCallResize)
		dayMapChart?.dispose()
		totalChart?.dispose()
		durationChart?.dispose()
	})
	// ===========================================METHODS==================================================
	//排名色
	const getOrderColor = (order) => {
		switch (order) {
			case 1:
				return orderColor[0]
			case 2:
				return orderColor[1]
			case 3:
				return orderColor[2]
			default:
				return orderColor[3]
		}
	}
	const getOrderRate = (rate) => {
		// const total = orderList.value.reduce((prev, cur) => {
		// 	return prev + Number(cur.rate)
		// }, 0)
		return ((Number(rate) / baseNum.value) * 100).toFixed(2) + '%'
	}
	// tooltip添加点击事件处理函数
const dayCallTooltipItemClick = (area, label, url) => {
		console.log('www');
		curAreaInfo.value.area = area
		curAreaInfo.value.label = label
		currentAudioUrl.value = url // 这里替换为实际的音频URL
		showAudioPlayer.value = true
		// 添加延时以确保 DOM 更新后再执行自动播放
		nextTick(() => {
			if (audioRef.value) {
				audioRef.value.load() // 重新加载音频
				audioRef.value.play().catch((e) => {
					alert('自动播放失败:')
				})
			}
		})
	}
	// ===========================================REQUEST==================================================
	const getData = async () => {
		const res = await biChartApi.getResultByType('TODAY_CALL_ANALYSIS_DAY')
		return JSON.parse(res.biResult)
	}
</script>
<style lang="less" scoped>
	#dayCallAnalysis {

		.statis-title {
			font-size: 18px;
			font-weight: 600;
			text-align: left;
		}
		// 数字统计
		.count {
			.count-content {
				display: grid;
				grid-template-columns: 1fr 1fr 1fr 1fr;
				height: 80px;
				.count-item {
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					align-items: center;
					.count-title {
						font-size: 16px;
					}
					.count-num {
						span:nth-child(1) {
							font-size: 38px;
							font-weight: 800;
							color: #bae0ff;
						}
						span:nth-child(2) {
							font-size: 18px;
							font-weight: 700;
						}
					}
				}
			}
		}
		.statis {
			display: flex;
			margin-top: 10px;
			height: calc(100% - 188px);
			//排行榜
			.statis-order {
				width: 18%;
				display: flex;
				flex-direction: column;
				.statis-order-list {
					flex: 1;
					// display: flex;
					// flex-direction: column;
					// justify-content: space-between;
					overflow-y: auto;
					//滚动条样式
					&::-webkit-scrollbar {
						display: none;
					}
					// &::-webkit-scrollbar {
					// 	width: 6px;
					// 	height: 6px;
					// }
					// &::-webkit-scrollbar-thumb {
					// 	background: #3d76f6;
					// 	border-radius: 3px;
					// }
					// &::-webkit-scrollbar-track {
					// 	background: rgba(255, 255, 255, 0.1);
					// 	border-radius: 3px;
					// }
					.list-item {
						display: grid;
						grid-template-columns: 0.5fr 1.5fr 2fr 1.5fr;
						padding-bottom: 10px;
						text-align: center;
						.list-item-num {
							border-radius: 2px;
						}
						.list-item-bar {
							display: flex;
							align-items: center;
							p {
								border-radius: 2px;
								background: linear-gradient(to right, #87b0f3, #0b22c4);
								margin: 0 0 0 0;
								height: 12px;
							}
						}
					}
				}
			}
			// 省份分布
			.statis-map {
				width: 60%;
				margin: 0 10px;
				display: flex;
				flex-direction: column;
				position: relative;
				#proviceMap {
					flex: 1;
				}
				//录音控件样式
				.audio-player {
					position: absolute;
					left: 20px;
					bottom: 20px;
					width: 450px;
					background: #18233e; // 移除透明度
					border: 1px solid #1e4b9c;
					border-radius: 4px;
					padding: 10px;
					color: #fff;

					.player-header {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 10px;
						font-size: 14px;

						.close-btn {
							cursor: pointer;
							font-size: 20px;
							&:hover {
								color: #5794f7;
							}
						}
					}

					.audio-control {
						width: 100%;
						height: 25px;
						/** 去掉默认的背景颜色 */
						&::-webkit-media-controls-enclosure {
							background-color: #8eaeee;
						}
					}
				}
			}
			/* 圆形图表 */
			.statis-callout {
				flex: 1;
				.total,
				.duration {
					width: 100%;
					height: 50%;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					> div {
						flex: 1;
					}
				}
			}
		}
	}
</style>
